<template>
	<el-tree
		v-if="!props.split"
		v-bind="$attrs"
		:node-key="$props.nodeKey"
		style="width: 100%"
		:data="data"
		:default-checked-keys="modelValue"
		@check="change"
	></el-tree>
	<el-tree
		v-else
		v-bind="$attrs"
		:node-key="$props.nodeKey"
		style="width: 100%"
		:data="data"
		:default-checked-keys="splitCheckKeys"
		@check="change"
	></el-tree>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
const props = defineProps(['modelValue', 'data', 'split', 'nodeKey'])
const emit = defineEmits(['update:modelValue'])

const splitCheckKeys = computed(() => {
	let keys = []
	const loop = function (data, select) {
		data.map(v => {
			if (v.children && v.children.length) {
				loop(v.children, select)
			} else {
				if (select.includes(v[props['nodeKey']])) {
					keys.push(v[props['nodeKey']])
				}
			}
		})
	}
	loop(props.data, props.modelValue)
	return keys
})

const change = (p1, p2) => {
	if (!props.split) {
		emit('update:modelValue', p2.checkedKeys)
	} else {
		emit('update:modelValue', [...p2.halfCheckedKeys, ...p2.checkedKeys])
	}
}
</script>
